bl_info = {
    "name": "Custom Vector Property to UV",
    "author": "moshi",
    "version": (1, 0),
    "blender": (3, 0, 0),
    "location": "Properties > Object Data > Custom Properties to UV",
    "description": "Assign custom vector properties to UV coordinates",
    "category": "Mesh",
}

import bpy
from bpy.props import StringProperty
from bpy.types import Operator, Panel

class MESH_OT_custom_prop_to_uv(Operator):
    """Assign selected custom vector property to UV coordinates"""
    bl_idname = "mesh.custom_prop_to_uv"
    bl_label = "Assign to UV"
    bl_options = {'REGISTER', 'UNDO'}
    
    property_name: StringProperty(
        name="Property Name",
        description="Name of the custom vector property to assign"
    )
    
    def execute(self, context):
        obj = context.active_object
        
        # Check if object is valid
        if not obj or obj.type != 'MESH':
            self.report({'ERROR'}, "Active object is not a mesh")
            return {'CANCELLED'}
        
        mesh = obj.data
        
        # Check if property exists
        if self.property_name not in mesh.attributes:
            self.report({'ERROR'}, f"Property '{self.property_name}' not found")
            return {'CANCELLED'}
        
        attr = mesh.attributes[self.property_name]
        
        # Check if property is a vector type
        if attr.data_type not in {'FLOAT2', 'FLOAT3', 'FLOAT4', 'INT2', 'INT3', 'INT4'}:
            self.report({'ERROR'}, f"Property '{self.property_name}' is not a vector type")
            return {'CANCELLED'}
        
        # Create UV layer if needed
        if not mesh.uv_layers:
            mesh.uv_layers.new(name="CustomPropertyUV")
        
        uv_layer = mesh.uv_layers.active
        
        # Assign property values to UVs
        # For higher dimensions, we just take the first two components
        try:
            for loop in mesh.loops:
                # Get the attribute value for this loop
                if attr.domain == 'POINT':
                    val = attr.data[loop.vertex_index].vector
                else:  # 'FACE' or 'CORNER' domain
                    val = attr.data[loop.index].vector
                
                # Assign first two components to UV
                uv_layer.data[loop.index].uv = (val[0], val[1])
            
            self.report({'INFO'}, f"Successfully assigned '{self.property_name}' to UVs")
            return {'FINISHED'}
            
        except Exception as e:
            self.report({'ERROR'}, f"Error during assignment: {str(e)}")
            return {'CANCELLED'}


class MESH_PT_custom_prop_to_uv_panel(Panel):
    """Panel for Custom Property to UV conversion"""
    bl_label = "Custom Properties to UV"
    bl_idname = "MESH_PT_custom_prop_to_uv_panel"
    bl_space_type = 'PROPERTIES'
    bl_region_type = 'WINDOW'
    bl_context = "data"
    
    def draw(self, context):
        layout = self.layout
        obj = context.active_object
        
        if not obj or obj.type != 'MESH':
            layout.label(text="Select a mesh object first")
            return
        
        mesh = obj.data
        
        # Get all vector attributes
        vector_attrs = [attr for attr in mesh.attributes 
                       if attr.data_type in {'FLOAT2', 'FLOAT3', 'FLOAT4', 'INT2', 'INT3', 'INT4'}]
        
        if not vector_attrs:
            layout.label(text="No vector attributes found")
            return
        
        # Property selector
        layout.label(text="Vector Property:")
        prop_box = layout.box()
        
        for attr in vector_attrs:
            op = prop_box.operator("mesh.custom_prop_to_uv", text=attr.name)
            op.property_name = attr.name
        
        layout.separator()
        layout.label(text="Note: For 3D+ vectors, only X and Y components are used")


def register():
    bpy.utils.register_class(MESH_OT_custom_prop_to_uv)
    bpy.utils.register_class(MESH_PT_custom_prop_to_uv_panel)


def unregister():
    bpy.utils.unregister_class(MESH_OT_custom_prop_to_uv)
    bpy.utils.unregister_class(MESH_PT_custom_prop_to_uv_panel)


if __name__ == "__main__":
    register()
